import Cesium from '../Ces/Cesium'
function ImageryLayer() {

}

ImageryLayer.prototype._reprojectTextureNEW = function (
  frameState,
  imagery,
  needGeographicProjection,
) {
  const texture = imagery.textureWebMercator || imagery.texture;
  const context = frameState.context;

  const that = this;
  const colorCommandFunc = this._imageryProvider.createComputeCommand;

  if (colorCommandFunc) {
    imagery.addReference()
    const computeCommand = colorCommandFunc(this, texture, imagery, context);
    computeCommand.persists = true;
    computeCommand.owner = this;
    computeCommand.canceled = function () {
      imagery.state = Cesium.ImageryState.TEXTURE_LOADED
      imagery.releaseReference()
    }

    computeCommand.postExecute = function (outputTexture) {
      if (computeCommand.postExecute2) {
        computeCommand.postExecute2();
      }
      if (texture._id != outputTexture._id) {
        const destroy = outputTexture.destroy
        outputTexture.destroy = () => {
          texture.destroy()
          return destroy.bind(outputTexture)()
        }
      }
      if (imagery.textureWebMercator) {
        imagery.textureWebMercator = outputTexture;
      } else {
        imagery.texture = outputTexture;
      }
      imagery.releaseReference()
      that._reprojectTextureOld(frameState,
        imagery,
        true);
    }
    this._reprojectComputeCommands.push(computeCommand);
  } else {
    that._reprojectTextureOld(frameState,
      imagery,
      needGeographicProjection);
  }
}

let ImageryLayerInjected = false;

ImageryLayer.inject = function () {
  if (ImageryLayerInjected) {
    return;
  }
  ImageryLayerInjected = true;
  Cesium.ImageryLayer.prototype._reprojectTextureOld = Cesium.ImageryLayer.prototype._reprojectTexture;
  Cesium.ImageryLayer.prototype._reprojectTexture = ImageryLayer.prototype._reprojectTextureNEW;
}

export default ImageryLayer;
